package cn.tonyandmoney.baidu.asr.entity;

import android.text.TextUtils;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;

/**
 * 语义识别结果
 * 平铺的结果
 */
public class NluResult {


    private String rawText;
    private String parsedText;
    private String domain;
    private String intent;

    private String results;

    private HashMap<String, String> mObjMap = new HashMap<>();

    public NluResult() {
    }

    public void setResults(String results) {
        this.results = results;
    }

    public String getResults() {
        return results;
    }

    public String getRawText() {
        return rawText;
    }

    public void setRawText(String rawText) {
        this.rawText = rawText;
    }

    public String getParsedText() {
        return parsedText;
    }

    public void setParsedText(String parsedText) {
        this.parsedText = parsedText;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getIntent() {
        return intent;
    }

    public void setIntent(String intent) {
        this.intent = intent;
    }

    public void addObj(String key, String value) {
        mObjMap.put(key, value);
    }

    public boolean hasNluResult() {
        return !TextUtils.isEmpty(domain) && !TextUtils.isEmpty(intent);
    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }

    public static NluResult fromJson(String json) {
        try {
            NluResult result = new NluResult();
            JSONObject jsonObject = new JSONObject(json);
            result.setRawText(jsonObject.getString("raw_text"));
            if (jsonObject.has("parsed_text"))
                result.setParsedText(jsonObject.getString("parsed_text"));
            if (jsonObject.has("results")) {
                JSONArray jsonArray = jsonObject.getJSONArray("results");
                result.setResults(jsonArray.toString());
                if (!jsonArray.isNull(0)) {
                    JSONObject object = jsonArray.getJSONObject(0);
                    result.setDomain(object.getString("domain"));
                    result.setIntent(object.getString("intent"));
                    JSONObject rObj = object.getJSONObject("object");
                    Iterator<String> keys = rObj.keys();
                    if (keys.hasNext()) {
                        String key = keys.next();
                        result.addObj(key, rObj.getString(key));
                    }
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
